package org.xs.object.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.xs.object.dao.product.Product;
import org.xs.object.dao.product.ProductRepository;
import org.xs.object.dao.page.PageResquest;
import org.xs.object.dao.page.PageResult;
import org.xs.object.service.IProductService;
import org.xs.object.utils.AilOssUtil;
import org.xs.object.utils.ProductLogoOssUtil;
import org.xs.object.utils.R;
import org.xs.object.utils.ResponseEnum;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class ProductService implements IProductService {
    ProductRepository productRepository;
    PageResult pageResult;
    PageResquest pageResquest;
    ProductLogoOssUtil productLogoOssUtil;
    FileUpLoadService fileUpLoadService;


    @Autowired
    public ProductService(
            ProductRepository productRepository,
            PageResult pageResult,
            PageResquest pageResquest,
            ProductLogoOssUtil productLogoOssUtil,
            FileUpLoadService fileUpLoadService) {
        this.productRepository = productRepository;
        this.pageResult = pageResult;
        this.pageResquest = pageResquest;
        this.productLogoOssUtil = productLogoOssUtil;
        this.fileUpLoadService = fileUpLoadService;
    }
    //查询商品列表(分页)
    /*
    * @param pageNum
    * @param pageSize
    * @return  R
    * 1.校验参数
    * 2.分页查询
    * 3.查询商品列表
    * 4.返回结果
     */
    @Override
    public R postProductList(PageResquest pageRequest) {
        //校验参数
        int currentPage = (pageRequest.getPageNum() != null && pageRequest.getPageNum() > 0) ? pageRequest.getPageNum() : 1;
        int currentPageSize = (pageRequest.getPageSize() != null && pageRequest.getPageSize() > 0) ? pageRequest.getPageSize() : 3;
        String currentSort = pageRequest.getSort()!=null?pageRequest.getSort():"id";
         Sort sort = Sort.by(Sort.Direction.DESC, currentSort);
        //分页查询
        Pageable pageable = PageRequest.of(currentPage - 1, currentPageSize, sort);
        //查询商品列表
        Page<Product> productList = productRepository.findAll(pageable);
        //返回结果
        PageResult Result =new PageResult();
        Result.setTotalPage(productList.getTotalPages());
        Result.setTotalCount(productList.getTotalElements());
        Result.setTotal(productList.getSize());
        Result.setItems(productList.getContent());
        return R.ok(Result);
    }
    //根据商品ID查询商品详情
    //1.校验参数
    @Override
    public R getProductById(Integer id) {
        if (id == null || id < 1) {
            return R.error(ResponseEnum.PARAM_ERROR);
        }
        Optional  productopt = productRepository.findById(id);
        if (!productopt.isPresent()){
            return R.error(ResponseEnum.PRODUCT_NOT_EXIST);
        }
        Product product = (Product) productopt.get();
        return R.ok(product);
    }
    @Override
    public R getProductById(ArrayList<Integer> ids) {
        if (ids == null || ids.size() < 1) {
            return R.error(ResponseEnum.PARAM_ERROR);
        }
        ArrayList<Product> productListById = new ArrayList<>();
        ids.stream().forEach(id-> {
            if (id < 1) {
                return;
            }
            Optional<Product> optional = productRepository.findById(id);
            if (!optional.isPresent()) {
                return;
            }
            productListById.add(optional.get());
        });
        if (productListById.size() != ids.size()){
            return R.error(ResponseEnum.PRODUCT_NOT_EXIST);
        }
        //Product product = productRepository.findById(id).get();
        return R.ok(productListById);
    }
    //根据商品名称查询商品列表
    @Override
    public R getProductsByName(String name) {
        if (name == null) {
            return R.error(ResponseEnum.PARAM_ERROR);
        }
        List<Product> productListByName = productRepository.findByProductName(name);
        if (productListByName.size() == 0){
            return R.error(ResponseEnum.PRODUCT_NOT_EXIST);
        }
        return R.ok(productListByName);
    }
    @Override
    public R getProductsByName(ArrayList<String> names) {
        if (names == null || names.size() < 1) {
            return R.error(ResponseEnum.PARAM_ERROR);
        }
        ArrayList<Product> productListByName = new ArrayList<>();
        names.stream().forEach(name -> {
            if (name == null) {
                return;
            }
            List<Product> productListByName1 = productRepository.findByProductName(name);
            productListByName.addAll(productListByName1);
        });
        return R.ok(productListByName);
    }
    //根据商品品牌查询商品列表
    @Override
    public R getProductsByBrand(String brand) {
        if (brand == null) {
            return R.error(ResponseEnum.PARAM_ERROR);
        }
        List<Product> productListByBrand = productRepository.findByBrand(brand);
        return R.ok(productListByBrand);
    }
    @Override
    public R getProductsByBrand(ArrayList<String> brands) {
        if (brands == null || brands.size() < 1) {
            return R.error(ResponseEnum.PARAM_ERROR);
        }
        ArrayList<Product> productListByBrand = new ArrayList<>();
        brands.stream().forEach(brand -> {
            if (brand == null) {
                return;
            }
            List<Product> productListByBrand1 = productRepository.findByBrand(brand);
            productListByBrand.addAll(productListByBrand1);
        });
        return R.ok(productListByBrand);
    }

    //添加商品
    /*
    * @param product
    * @return R
    * 1.校验参数
    * 2.添加商品
    * 3.返回结果
     */
    @Override
    public R addProduct(Product product) {
        if (product == null){
            return R.error(ResponseEnum.PARAM_ERROR);
        }
        product.setCreate_time(LocalDateTime.now());
        product.setUpdate_time(LocalDateTime.now());
        productRepository.save(product);
        return R.ok();
    }
    @Override
    public R addProduct(ArrayList<Product>  products) {
        if (products == null || products.size() < 1){
            return R.error(ResponseEnum.PARAM_ERROR);
        }
        products.stream().forEach(product -> {
            product.setCreate_time(LocalDateTime.now());
            product.setUpdate_time(LocalDateTime.now());
            productRepository.save(product);
        });
        return R.ok();
    }
    //修改商品
    @Transactional
    @Override
    public R updateProduct(Product product) {
        if (product == null||product.getId()<1){
            return R.error(ResponseEnum.PARAM_ERROR);
        }
        product.setUpdate_time(LocalDateTime.now());
        productRepository.updateProduct(
                product.getProduct_name(),
                product.getMoney(),
                product.getBrand(),
                product.getOperation(),
                product.getLogo_url(),
                product.getUpdate_time(),
                product.getId());
        return R.ok();
    }
    @Transactional
    @Override
    public R updateProduct(ArrayList< Product>  products) {
        if (products == null||products.size() < 1){
            return R.error(ResponseEnum.PARAM_ERROR);
        }
        products.stream().forEach(product -> {
            if (product.getId()>=1){
                product.setUpdate_time(LocalDateTime.now());
                productRepository.updateProduct(
                        product.getProduct_name(),
                        product.getMoney(),
                        product.getBrand(),
                        product.getOperation(),
                        product.getLogo_url(),
                        product.getUpdate_time(),
                        product.getId());
            }
        });
        return R.ok();
    }

    //删除商品
    @Transactional
    @Override
    public R deleteProduct(Integer id) {
        if (id == null || id < 1) {
            return R.error(ResponseEnum.PARAM_ERROR);
        }
        productRepository.deleteById(id);
        return R.ok();
    }
    @Transactional
    @Override
    public R deleteProduct(ArrayList<Integer>  ids) {
        if (ids == null || ids.size() < 1) {
            return R.error(ResponseEnum.PARAM_ERROR);
        }
        for (Integer id : ids) {
            productRepository.deleteById(id);
        }
        return R.ok();
    }

    //上传商品logo
    @Override
    public R uploadProductLogo(MultipartFile file) {
        if (file == null) {
            return R.error(ResponseEnum.PARAM_ERROR);
        }
        R result = fileUpLoadService.uploadProductLogo(file);
        String url= result.getData().toString();
        return R.ok( url);
    }

    @Override
    public R deleteProductLogo(Integer id) {
        if (id == null || id < 1) {
            return R.error(ResponseEnum.PARAM_ERROR);
        }
        if (!productLogoOssUtil.deleteLogoFile(id)){
            return R.error(ResponseEnum.FILE_DELETE_ERROR);
        }
        productRepository.deleteLogoUrlById(id);
        return R.ok();
    }
}
